package com.lt.common;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * 数组文件缓存工具
 *
 * @author luotian
 */
public class FileCacheHelper {

    private static FileCacheHelper instance;

    protected FileCacheHelper() {
    }

    public static FileCacheHelper getInstance() {
        if (instance == null) {
            synchronized (FileCacheHelper.class) {
                instance = new FileCacheHelper();
            }
        }
        return instance;
    }

    public <T> void setData(List<T> list, String name) {
        File Cache = new File(getCacheDir(), name);
        if (Cache.exists()) {
            Cache.delete();
        }
        ObjectOutputStream outputStream = null;
        try {
            outputStream =
                    new ObjectOutputStream(new FileOutputStream(Cache));
            outputStream.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIO(outputStream);
        }
    }

    public <T> List<T> getData(String name) {
        File cache = new File(getCacheDir(), name);
        if (!cache.exists()) {
            return null;
        }
        FileInputStream fis = null;
        ObjectInputStream inputStream = null;
        try {
            fis = new FileInputStream(cache);
            inputStream = new ObjectInputStream(fis);
            List<T> list = (List<T>) inputStream.readObject();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIO(fis);
            CloseUtils.closeIO(inputStream);
        }
        return null;
    }

    public void removeCache(String name) {
        File Cache = new File(getCacheDir(), name);
        if (Cache.exists()) {
            Cache.delete();
        }
    }

    /**
     * @return 返回缓存文件夹
     */
    protected File getCacheDir() {
        return FileHelper.getInstance().getInternalCacheDirectory();
    }
}
